package com.example.systemserver.config;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.ResultBean;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

//拦截器
@Component
@Order(1)
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        servletResponse.setContentType("application/json;charset=utf-8");
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.equals("/account/login")||requestURI.startsWith("/file/getImage")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = httpServletRequest.getHeader("token");
        if (token == null){
            ResultBean  resultBean = new ResultBean(401,"请先登录",null);
            servletResponse.getWriter().write(JSONUtil.toJsonStr(resultBean));
            return;
        }
        try{
            JWTUtil.verify(token, "1234567".getBytes(StandardCharsets.UTF_8));
            JWT jwt =  JWTUtil.parseToken(token);
            Object timeout = jwt.getPayload("timeout");
            NumberWithFormat numberWithFormat = (NumberWithFormat) timeout;
            long timeout1 = numberWithFormat.longValue();
            //验证令牌是否超时
            //强类型转换
//            long timeout = (long) jwt.getPayload("timeout");
            if (System.currentTimeMillis() > timeout1){
                //程序直接进入错误处理程序（catch），程序不再往下执行
              throw new RuntimeException("令牌已超时");
            }
        }catch (Exception e){
            ResultBean  resultBean = new ResultBean(401,"无效令牌",null);
            servletResponse.getWriter().write(JSONUtil.toJsonStr(resultBean));
            return;
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
